package com.yhh.common.exception;

import com.yhh.common.base.ret.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Slf4j //日志
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
     public ApiResult exceptionHandler(Exception e){
        log.error("异常信息:" + e.getMessage());
        e.printStackTrace();

        // 业务功能异常
        if(e instanceof BusinessException){
            return ApiResult.error(e.getMessage());
        }

        // 数据校验失败异常
        if(e instanceof MethodArgumentNotValidException || e instanceof BindException){
            BindingResult bindResult = null;
            if(e instanceof MethodArgumentNotValidException){
                bindResult =((MethodArgumentNotValidException)e).getBindingResult();
            }
            if(e instanceof java.net.BindException){
                bindResult = ((BindException)e).getBindingResult();
            }
            // 获取异常信息列表
            List<FieldError> fieldErrors = bindResult.getFieldErrors();
            StringBuffer msg = new StringBuffer();
            for(int i = 0; i< fieldErrors.size();i++){
                msg.append(fieldErrors.get(i).getField());// 拿到了参数名称
                msg.append(":");
                msg.append(fieldErrors.get(i).getDefaultMessage());// 拿到了错误消息
                if(i < fieldErrors.size() - 1){
                    msg.append(",");
                }
            }
            return ApiResult.error(msg.toString());
        }

        return ApiResult.error();
     }
}
